import { FC, useEffect, useState } from "react";
import { Notification,Message } from "@arco-design/web-react";
import webSocketService from "./websocket.tsx";
import sound from "../assets/notification-sound.mp3";
import { useNavigate } from "react-router-dom";
import { ViewVideoRecordModal } from "../components/ViewVideoRecordModal";
import ButtonGroup from "@mui/material/ButtonGroup";
import Button from "@mui/material/Button";
import { useAPI } from "../hooks/useAPI.ts";
import dayjs from "dayjs";


interface Notification2Props {
  userId: string;
}

export const Notification2: FC<Notification2Props> = ({}) => {
  const api = useAPI();

  const [videoModals, setVideoModals] = useState<
    Array<{
      key: string;
      id: string;
      userId: number;
      suid: string;
      startTime: string;
      isOpen: boolean;
    }>
  >([]);

  const [refresh, setRefresh] = useState(false);
  const navigator = useNavigate();

  const [notificationIds, setNotificationIds] = useState<string[]>([]);

  useEffect(() => {
    // Example effect that runs when refresh is toggled
    window.localStorage.setItem("refresh", refresh.toString());
    // You can use this effect to reload data or perform another side-effect
  }, [refresh]);

  const notify = (notification: any) => {
    // console.log("notify===", notification);
    const id = notification.riskId; //`${Date.now()}`;
    let arr = notificationIds;
    addIfNotExists(arr, id);
    setNotificationIds([...arr]); // 保存 id 到 ref
    // console.log("notificationIds2222", notificationIds);
    const key = notification.subject;
    const data = notification.subject.split(",");

    const userId = parseInt(data[0]);
    const suid = data[1];
    const startTime = data[2];

    setVideoModals((prev) => [
      ...prev,
      {
        key,
        id,
        userId,
        suid,
        startTime,
        isOpen: false,
      },
    ]);

    Notification.info({
      id,
      title: `${notification.title}`,
      content: `${notification.body}`,
      duration: 0,
      btn: (
        <ButtonGroup>
          <audio
            autoPlay
            loop={notification.type == "warning" ? false : true}
            id="auto"
            src={sound}
          ></audio>
          {data[0] && (
            <Button
              variant="outlined"
              size="small"
              color="success"
              onClick={(e) => {
                e.preventDefault();
                setRefresh((prev) => !prev);
                Notification.remove(id);
                navigator(`/homepage/seniorReport/${data[0]}`);
              }}
            >
              前往工作台
            </Button>
          )}
          <Button
            variant="outlined"
            size="small"
            color="secondary"
            onClick={(e) => {
              e.preventDefault();
              setRefresh((prev) => !prev);
              Notification.remove(id);
              navigator(`/homepage/risk`);
            }}
          >
            前往风险管理
          </Button>
          {data[1] && (
            <Button
              variant="outlined"
              size="small"
              color="info"
              onClick={(e) => {
                e.preventDefault();
                Notification.remove(id);
                setVideoModals((prev) =>
                  prev.map((modal) =>
                    modal.key === key ? { ...modal, isOpen: true } : modal
                  )
                );
              }}
            >
              查看回放
            </Button>
          )}
        </ButtonGroup>
      ),
    });
  };

  const closeModal = (key: string) => {
    Notification.remove(key);
    setVideoModals((prev) =>
      prev.map((modal) =>
        modal.key === key ? { ...modal, isOpen: false } : modal
      )
    );
  };
  useEffect(() => {
    //  let data = {
    //   title: "notification.title",
    //   body: "notification.body",
    //   subject: "notification.subject",
    //   riskId: "1",
    //   // url:'3b75fc57-6a37-4c66-9b1f-513fe1e0191f_fall_down'
    //   url:'https://picx.zhimg.com/v2-48b242a6ad6f31028439311e5c710913_1440w.jpg'
    // };

    // let data2 = {
    //   title: "notification.title111",
    //   body: "notification.body1111",
    //   subject: "notification.subject",
    //   riskId: "2",
    //   // url:'ed5620a9-93e0-44dd-b566-0a3192a0322a_fall_down'
    //   url:'https://pic1.zhimg.com/v2-aa6a3c14fead46279be31a4821cc336c_1440w.jpg'
    // };

    // setTimeout(() => {
    //   notify(data);
    // }, 1000);
    // setTimeout(() => {
    //   notify(data2);
    // }, 3000);

    // setInterval(() => {
    //   data.title = "remove"+ getRandomInt(0, 2)
    //   data.riskId =  getRandomInt(0, 2).toString()

    //   if (data.title == "remove0" && notificationIds.includes(data.riskId)) {
    //     console.log("remove", data.subject);
    //     clearNotification(data.riskId);
    //   } else {
    //     console.log("notify", data.subject);
    //     notify(data);
    //   }
    // }, 3000);

    // setTimeout(() => {
    //   data2.title = "remove"; //+ getRandomInt(0, 2),

    //   if (data2.title == "remove" && notificationIds.includes(data2.riskId)) {
    //     console.log("remove", data2.subject);
    //     clearNotification(data2.riskId);
    //   } else {
    //     console.log("notify", data.subject);
    //     notify(data2);
    //   }
    // }, 8000);
    // let data = {
    //   riskId:
    //     "297,a6c86006-48af-482b-9e02-c81396f0dab6_fall_down,2025-11-03 14:22:06",
    //   body: "房间【8106】有新的消息提示：【2025-11-03 14:22:06】检测到【摔倒】，请及时处理。",
    //   subject:
    //     "297,a6c86006-48af-482b-9e02-c81396f0dab6_fall_down,2025-11-03 14:22:06",
    //   title: "【来自8106的风险警报】",
    // };
    // notify(data);

    // Connect to WebSocket
    webSocketService.connect();

    // Subscribe to a topic (e.g., '/topic/messages')
    webSocketService.subscribe(`/topic/notification/`, (message) => {
      if (message.body) {
        const notification = JSON.parse(message.body);
        notification.riskId = notification.subject;
        // console.log("notification==message.body==", notification);
        if (
          notification.title == "remove"
          // &&notificationIds.includes(notification.riskId)
        ) {
          clearNotification(notification.riskId, notification.subject);
        } else {
          notify(notification);
        }
      }
    });

    // Clean up on component unmount
    return () => {
      webSocketService.disconnect();
      setNotificationIds([]);
    };
  }, []);
  // const getRandomInt = (min: number, max: number) => {
  //   min = Math.ceil(min);
  //   max = Math.floor(max);
  //   return Math.floor(Math.random() * (max - min + 1)) + min;
  // };

  const addIfNotExists = (array: any, id: string) => {
    if (array.indexOf(id) === -1) {
      array.push(id);
    }
  };

  // 从其他地方清除通知
  const clearNotification = (riskId: any, key: string) => {
    Notification.remove(riskId);
    if (notificationIds.includes(riskId)) {
      let arr = notificationIds.filter((item: any) => item !== riskId);
      setNotificationIds(arr);
    }
    // 同时清理对应的模态框状态
    setVideoModals((prev) => prev.filter((modal) => modal.key !== key));
  };

  const deleteRecord = (id: number, suid: string,userId: number | string) => {
    api
      .deleteRiskProcessingLog({
        id,
        userId: userId,
        suid,
        data: {
          pics: "",
          files: "",
          method: 0,
          report: {
            userId: window.localStorage.getItem("loggedUserId"),
            nickName: window.localStorage.getItem("loggedNickName"),
          },
          time: dayjs().format("YYYY-MM-DD HH:MM:s"),
        },
      })
      .then((r) => {
        if (r.data.code == "3001") {
          Message.info("操作成功");
          setRefresh(!refresh);
        } else {
          Message.info("操作失败");
        }
      });
  };

  return (
    <div>
      {videoModals.map((modal) => (
        <ViewVideoRecordModal
          key={modal.key}
          videoList={modal.suid}
          id={modal.id}
          userId={modal.userId}
          visible={modal.isOpen}
          eventTime={modal.startTime}
          onClose={() => closeModal(modal.key)}
          refresh={() => setRefresh(!refresh)}
          report="null"
          deleteRecord={deleteRecord}
        />
      ))}
    </div>
  );
};
